//
//  ViewController.m
//  常驻线程
//
//  Created by LeeJay on 16/4/21.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) NSThread *thread;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething4) object:nil];
    self.thread.name = @"我是常驻线程";
    [self.thread start];

}

/**
 * 这条线程做完任务就直接挂了
 */
- (void)doSomething {
    
    NSLog(@"------做任务-----");
    
}

/**
 * 这种方式虽然能保住线程的命，但是这条线程就无法处理其他事件
 */
- (void)doSomething1 {
    
    while (1) { // 当前线程永远在处理这行代码
        NSLog(@"----------做任务----%@", [NSThread currentThread]);
    };
    
}

/**
 *  此种方法可以保住线程的命，但是不建议这种方法。
 */
- (void)doSomething2 {
    
    while (1) {
        NSLog(@"---------------");
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"***************");
    }
    
}

/**
 *  建议此种方法，在当前runloop中加入port
 */
- (void)doSomething3 {
    
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [runLoop run];
    
}

/**
 *  在子线程的runloop中加入timer
 */
- (void)doSomething4 {

    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    
}

- (void)run {
    NSLog(@"-------run-----");
}

- (void)test {
    
    NSLog(@"----------test----------%@", self.thread);
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
